//index.js
//获取应用实例
const app = getApp()
const commonService = require('../../service/common.js');
Page({
  data: {
    title:"登录",
    loading:false,
    code:"",
    refer:""
  },
  onLoad: function (options) {
    let refer = options.refer || "";
    this.setData({
      refer: refer
    });
    this.getCode();
  },
  onShow: function(options){
  },
  getCode(){
    wx.login({
      success: res => {
        this.setData({
          code:res.code
        })
      }
    })
  },
  getUserInfo(){
    wx.getUserInfo({
      success: res => {
        let data = res;
        delete data.errMsg;
        this.getToken({...data,code:this.data.code});
      }
    })
  },
  getToken(data){
    this.setData({
      loading:true
    })
    commonService.code2Session(data).then(res => {
      this.setData({
        loading: false
      })
      if(res.resCode == 0){
        this.getInfo({ ...data, sessionKey: res.object.session_key});
      }
    },res => {
      this.setData({
        loading: false
      })
    })
  },
  getInfo(data){
    commonService.getUserinfo({ ...data, appId: app.globalData.$config.APP_ID}).then(res => {
      if (res.resCode == 0){
        console.log(res);
        //
        let token = res.object.token;
        let userInfo = res.object;
        wx.setStorageSync("DT-TOKEN", token);
        wx.setStorageSync("DT-USERINFO", userInfo);
        app.globalData.userinfo = userInfo;
        app.globalData.token = token;
        if (this.data.refer) {
          let path = decodeURIComponent(this.data.refer);
          console.log('-----'+path);
          if(path == '/pages/index/index?'){
            path = '/pages/mine/index'
          }
          let serviceMethod = app.checkIsTab(path) ? wx.switchTab : wx.redirectTo;
          serviceMethod({
            url: path,
          })
        } else {
          wx.switchTab({
            url: "/pages/mine/index",
          })
        }
      }
    })
  }
})
